part of 'component.dart';

class FrameImage extends StatefulWidget {
  FrameImage({
    Key? key,
    required this.imgs,
    this.duration,
  }) : super(key: key) {
    assert(imgs.isNotEmpty);
  }
  final List<String> imgs;
  final Duration? duration;
  @override
  State<FrameImage> createState() => _FrameImageState();
}

class _FrameImageState extends State<FrameImage>
    with SingleTickerProviderStateMixin {
  late AnimationController ac;
  late Tween<int> ani;
  int currVal = 0;
  @override
  void initState() {
    if (widget.imgs.isEmpty) {
      return;
    }

    ac = AnimationController(
      vsync: this,
      duration:
          widget.duration ?? Duration(milliseconds: 300 * widget.imgs.length),
      lowerBound: 0,
      upperBound: widget.imgs.length.toDouble(),
    );
    ani = Tween(begin: 0, end: widget.imgs.length)..animate(ac);
    ac.forward();
    ac.addStatusListener((status) {
      if (status == AnimationStatus.completed) {
        ac.reset();
        ac.forward(from: 0);
      }
    });
    ac.addListener(() {
      var idx = ac.value.toInt();
      if (currVal == idx) {
        return;
      }
      currVal = idx;
      setState(() {});
    });
    super.initState();
  }

  @override
  void dispose() {
    ac.dispose();
    super.dispose();
  }

  @override
  Widget build(BuildContext context) {
    if (widget.imgs.length <= ac.value.toInt()) {
      return const SizedBox();
    }
    return Stack(
        children: widget.imgs
            .asMap()
            .map((key, value) => MapEntry(
                  key,
                  Visibility(
                    visible: key == currVal,
                    child: Image.asset(
                      widget.imgs[key],
                      fit: BoxFit.contain,
                    ),
                  ),
                ))
            .values
            .toList());
  }
}
